package com.study.hot.jetpack.paging

import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.study.hot.databinding.ActivityPaging3Binding
import com.study.hot.jetpack.paging.paging3.DataRecycleViewAdapter
import com.study.hot.jetpack.paging.paging3.PagingViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.jetbrains.anko.sdk27.coroutines.onClick

/**
 * <pre>
 *     author : slx
 *     time   : 2021/02/02
 *     desc   :
 * </pre>
 */
class Paging3Activity : AppCompatActivity() {

    private val pageViewModel: PagingViewModel by viewModels()

    lateinit var adapter: DataRecycleViewAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityPaging3Binding.inflate(layoutInflater)
        setContentView(binding.root)
        adapter = DataRecycleViewAdapter()
        binding.apply {
            pagingRecyclerView.adapter = adapter
            btnGetData.onClick {
                lifecycleScope.launch {
                    pageViewModel.getData().collectLatest {
                        adapter.submitData(it)
                    }
                }
            }
        }

        addListener()
    }

    // 添加加载监听
    private fun addListener() {
        // 普通方式
        adapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> Log.i("fauks", "is NotLoading")
                is LoadState.Loading -> Log.i("fauks", "is Loading")
                is LoadState.Error -> Log.i("fauks", "is Error")
            }
        }
    }
}